package com.pgyl.contract.service.base;

import com.pgyl.contract.exceptions.ValidationException;
import com.pgyl.contract.model.Contract;
import com.pgyl.contract.service.ContractService;
import com.pgyl.contract.validator.ContractValidator;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;

// 抽象模板类
public abstract class AbstractContractService<T extends Contract> implements ContractService<T> {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private ContractValidator<T> validator;

    private final Class<T> contractType;


    // 模板方法
    @Override
    public final void addContract(T contract) throws ValidationException {
        preAddContractProcessing();
        validator.validate(contract);
        specificAddContractProcessing(contract);
        postAddContractProcessing();
    }

    private void preAddContractProcessing() {
        // 公共前置处理
        //去除前后空格.........
    }

    private void postAddContractProcessing() {
        // 公共后置处理
    }

    protected abstract void specificAddContractProcessing(T contract);


    @SuppressWarnings("unchecked")
    protected AbstractContractService() {
        this.contractType = (Class<T>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public Class<T> getContractType() {
        return contractType;
    }
}
